import pygame
from settings import *
from support import *
from timer import Timer


"""
玩家类：定义游戏里玩家角色的各种操作
属性：
函数：
"""
# pygame.sprite.Sprite参数表明这是作为游戏对象类
class Player(pygame.sprite.Sprite):
	# pos:位置，group:组群
	def __init__(self, pos, group, collision_sprites, tree_sprites, interaction, soil_layer, toggle_shop):
		super().__init__(group)

		self.import_assets()
		self.status = 'down_idle'
		self.frame_index = 0

		# # 角色创建
		self.image = self.animations[self.status][self.frame_index]
		self.rect = self.image.get_rect(center=pos)
		# 角色所处层级
		self.z = LAYERS['main']

		# 移动参数
		self.direction = pygame.math.Vector2() # 角色二维数组的位置参数
		self.pos = pygame.math.Vector2(self.rect.center)
		self.speed = 200

		# 碰撞
		self.hitbox = self.rect.copy().inflate((-126, -70))
		self.collision_sprites = collision_sprites

		# 调用计时器
		self.timers = {
			'tool use': Timer(350, self.use_tool),
			'tool switch': Timer(200),
			'seed use': Timer(350, self.use_seed),
			'seed switch': Timer(200)
		}

		# 工具
		self.tools = ['hoe', 'axe', 'water']
		self.tool_index = 0
		self.selected_tool = self.tools[self.tool_index]

		# 种子
		self.seeds = ['corn', 'tomato']
		self.seed_index = 0
		self.selected_seed = self.seeds[self.seed_index]

		# 库存
		self.item_inventory = {
			'wood':   20,
			'apple':  20,
			'corn':   20,
			'tomato': 20
		}
		self.seed_inventory = {
			'corn': 5,
			'tomato': 5,
		}
		self.money = 200

		# interaction
		self.tree_sprites = tree_sprites
		self.interaction = interaction
		self.sleep = False
		self.soil_layer = soil_layer
		self.toggle_shop = toggle_shop

		# sound
		self.watering = pygame.mixer.Sound('../audio/water.mp3')
		self.watering.set_volume(0.2)

	# 使用工具
	def use_tool(self):
		print("tool use")
		if self.selected_tool == 'hoe':
			self.soil_layer.get_hit(self.target_pos)
		if self.selected_tool == 'axe':
			for tree in self.tree_sprites.sprites():
				if tree.rect.collidepoint(self.target_pos):
					tree.damage()
		if self.selected_tool == 'water':
			self.soil_layer.water(self.target_pos)
			self.watering.play()

	# 获取使用工具目标位置
	def get_target_pos(self):
		self.target_pos = self.rect.center + PLAYER_TOOL_OFFSET[self.status.split('_')[0]]

	# 使用种子
	def use_seed(self):
		if self.seed_inventory[self.selected_seed] > 0:
			self.soil_layer.plant_seed(self.target_pos, self.selected_seed)
			self.seed_inventory[self.selected_seed] -= 1

	# 导入人物的各种运动动作素材
	def import_assets(self):
		self.animations = {'up': [],'down': [],'left': [],'right': [],
						   'right_idle':[],'left_idle':[],'up_idle':[],'down_idle':[],   # 空闲
						   'right_hoe':[],'left_hoe':[],'up_hoe':[],'down_hoe':[],   # 锄地
						   'right_axe':[],'left_axe':[],'up_axe':[],'down_axe':[],   # 斧头砍
						   'right_water':[],'left_water':[],'up_water':[],'down_water':[]}    # 浇水

		for animation in self.animations.keys():
			full_path = '../graphics/character/' + animation
			self.animations[animation] = import_folder(full_path)

	# 角色动画(每个动作存在四张图片)
	def animate(self,dt):
		self.frame_index += 4 * dt
		if self.frame_index >= len(self.animations[self.status]):
			self.frame_index = 0

		self.image = self.animations[self.status][int(self.frame_index)]

	# 用户输入控制移动
	def input(self):
		# 获取用户输入
		keys = pygame.key.get_pressed()
		# 未使用工具并且未休息时
		if not self.timers['tool use'].active and not self.sleep:
			# 角色方向的输入
			if keys[pygame.K_UP]:
				self.direction.y = -1
				self.status = 'up'
			elif keys[pygame.K_DOWN]:
				self.direction.y = 1
				self.status = 'down'
			else:
				self.direction.y = 0  # 当输入不是上面的情况，恢复y的值为0，防止角色一直向上移动

			if keys[pygame.K_RIGHT]:
				self.direction.x = 1
				self.status = 'right'
			elif keys[pygame.K_LEFT]:
				self.direction.x = -1
				self.status = 'left'
			else:
				self.direction.x = 0

			# 工具的使用输入[空格键]
			if keys[pygame.K_SPACE]:
				# 激活工具的使用
				self.timers['tool use'].activate()
				self.direction = pygame.math.Vector2()
				self.frame_index = 0

			# 改变工具的使用[英文状态下的q键]
			if keys[pygame.K_q] and not self.timers['tool switch'].active:
				self.timers['tool switch'].activate()
				self.tool_index += 1
				self.tool_index  = self.tool_index if self.tool_index < len(self.tools) else 0
				self.selected_tool = self.tools[self.tool_index]

			# 种子的使用[ctrl键]
			if keys[pygame.K_LCTRL]:
				self.timers['seed use'].activate()
				self.direction = pygame.math.Vector2()
				self.frame_index = 0
				

			# 切换种子
			if keys[pygame.K_e] and not self.timers['seed switch'].active:
				self.timers['seed switch'].activate()
				self.seed_index += 1
				self.seed_index = self.seed_index if self.seed_index < len(self.seeds) else 0
				self.selected_seed = self.seeds[self.seed_index]

			# 交互
			if keys[pygame.K_RETURN]:
				print(f'用户按下Enter键')
				# 判断玩家是否在商人附近
				collided_interaction_sprite = pygame.sprite.spritecollide(self, self.interaction, False)
				if collided_interaction_sprite:
					# 在商人附近，打开商店菜单
					if collided_interaction_sprite[0].name == 'Trader':
						self.toggle_shop()
					else:   # 不在商人附近，不打开商店菜单
						self.status = 'left_idle'
						self.sleep = True

	# 获取角色的状态
	def get_status(self):
		
		# idle(角色没有移动)
		if self.direction.magnitude() == 0:
			self.status = self.status.split('_')[0] + '_idle'

		# tool use
		if self.timers['tool use'].active:
			self.status = self.status.split('_')[0] + '_' + self.selected_tool

	# 更新计时器
	def update_timers(self):
		for timer in self.timers.values():
			timer.update()

	# 碰撞功能的实现
	def collision(self, direction):
		for sprite in self.collision_sprites.sprites():
			if hasattr(sprite, 'hitbox'):
				if sprite.hitbox.colliderect(self.hitbox):
					if direction == 'horizontal':
						if self.direction.x > 0: # moving right
							self.hitbox.right = sprite.hitbox.left
						if self.direction.x < 0: # moving left
							self.hitbox.left = sprite.hitbox.right
						self.rect.centerx = self.hitbox.centerx
						self.pos.x = self.hitbox.centerx

					if direction == 'vertical':
						if self.direction.y > 0: # moving down
							self.hitbox.bottom = sprite.hitbox.top
						if self.direction.y < 0: # moving up
							self.hitbox.top = sprite.hitbox.bottom
						self.rect.centery = self.hitbox.centery
						self.pos.y = self.hitbox.centery

	# 角色运动
	def move(self,dt):

		# normalizing a vector(确保向量单位为1)，防止角色斜运动速度与水平运动不一致
		if self.direction.magnitude() > 0:
			self.direction = self.direction.normalize()

		# horizontal movement
		self.pos.x += self.direction.x * self.speed * dt
		self.hitbox.centerx = round(self.pos.x)
		self.rect.centerx = self.hitbox.centerx
		self.collision('horizontal')

		# vertical movement
		self.pos.y += self.direction.y * self.speed * dt
		self.hitbox.centery = round(self.pos.y)
		self.rect.centery = self.hitbox.centery
		self.collision('vertical')

	# 更新
	def update(self, dt):
		self.input()
		self.get_status()
		self.update_timers()
		self.get_target_pos()

		self.move(dt)
		self.animate(dt)
